package com.wushijia.highconcurrency.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * description:数组也能线程安全：AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray（普通的对象数组）
 *
 * @author yang
 * @date 2018/5/29 20:51
 */
public class AtomicIntegerFieldUpdateDemo {

  public static class Candidate {

    int id;
    volatile int score;
  }

  public final static AtomicIntegerFieldUpdater<Candidate> SCORE_UPDATE = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");

  public static AtomicInteger allScore = new AtomicInteger(0);

  public static void main(String[] args) throws InterruptedException {
    final Candidate candidate = new Candidate();
    Thread[] t = new Thread[10000];
    for (int i = 0; i < 10000; i++) {
      t[i] = new Thread() {
        @Override
        public void run() {
          if (Math.random() > 0.4) {
            SCORE_UPDATE.incrementAndGet(candidate);
            allScore.incrementAndGet();
          }
        }
      };
      t[i].start();
    }
    for (int i = 0; i < 10000; i++) {
      t[i].join();
    }
    System.out.println("score = " + candidate.score);
    System.out.println("allScore = " + allScore);
  }
}
